/**
 * Created by Foold on 14-2-15.
 */

/*
 * GET users listing.
 */
var cname  = require('path').basename(module.filename,'.js');
var routers = require('commons-dao')('article');
var ObjectID = require('mongodb').ObjectID;
var form = require('express-form');
var utils = require('my-utils');

var field = form.field;

function getRules(i18n){

    return [];

}

function showChildDetail(req,res,artcol,db){
    var id = req.params.id;
    artcol.findOne({_id:routers.ObjectID(id)},{fields:{_id:1,name:1,content:1,createDate:1}},function(err,arcdoc){

        db.close();
        res.render('frontal/child-content',{bean:arcdoc,layout:'child-detail'});

    });
}


function showChild(req,res,artcol,db){

    var rdata = {};
    var arcId = req.body["articlec.id"];
    db.collection('articlec',function(err,arcol){
        arcol.findOne({_id:routers.ObjectID(arcId)},{fields:{_id:1,name:1,url:1}},function(err,arcdoc){
            if(!arcdoc){
                res.render("404",{layout:false});
                db.close();
                return ;
            }
            if(arcdoc.url){//begin has url specified

                res.redirect(arcdoc.url);
                db.close();


            //end has url eepcified
            }else{

                db.collection('mainmenu', function(err, mcol) {
                    mcol.findOne({id:'onlyone'}, {fields:{content:1}}, function(err, menudoc) {


                            var limit = 10;
                            var p = req.query.p;
                            var skip = p;
                            if(!p || p<1)p = 1;
                            var start = (skip-1)*limit;
                            var aquery = {"articlec.id":arcId};
                            artcol.count(aquery,function(err,count){
                                artcol.find(aquery,
                                    {limit:limit,skip:start,fields:{_id:1,name:1,imagelist:1,articlec:1,createDate:1,content:1},sort:{createDate:-1}}

                                    ,function(err,results){
                                    results.toArray(function(err, artdocs){
                                        var baseurl = "/child/"+arcId;
                                        rdata.pagination =utils.pagination( count, p,baseurl,true);
                                        rdata.list = artdocs;
                                        rdata.layout='children';
                                        rdata.bean=arcdoc;
                                        if(artdocs){

                                            var len = artdocs.length;
                                            switch(len){
                                                case 0:
                                                    tempname='frontal/no-content';
                                                    break;
                                                case 1:
                                                    rdata.bean=artdocs[0];
                                                    tempname='frontal/content';
                                                    break;
                                                default:
                                                    tempname = 'frontal/newslist';

                                            }



                                        }else{
                                            tempname='frontal/content';
                                        }

                                        rdata.menu = {
                                            id:arcId,
                                            content:menudoc.content
                                        };


                                        console.log(rdata);
                                        res.render(tempname,rdata);
                                        db.close();
                                    });
                                });//end of find
                            });//end of count

                        });//end of collection article

                    });
            }



        });
    });


}

function homeData(req,res,artcol,db){
    //home page

    var homedata = {};
    var rdata = {};

    db.collection("articlec",function(err,arccol){

        arccol.findOne({area:"B"},function(err,bartcdoc){

            arccol.find({parentId:bartcdoc._id.toHexString()}
                ,{skip:0,limit:5,fields:{_id:1,name:1}}).toArray(function(err,bchildren){


                    artcol.find({"area":{$in:['A','C']}},{fields:{_id:1,name:1,articlec:1,area:1,imagelist:1},sort:{sort:-1}},function(err,result){
                        result.toArray(function(err, artdocs){

                            //----------------------------------------
                            ///console.log(artdocs);
                            if(err)console.log(err);



                            homedata['A']={
                                list:[]
                            };

                            homedata['C']={
                                list:{}
                            };

                            for(var a in artdocs){

                                (function(doc){
                                    var areaa = doc['area'];
                                    if(areaa=='A')
                                        homedata['A']['list'].push(doc);
                                    else{
                                        homedata['C']['list'][doc['articlec']['id']]=doc;
                                    }

                                })(artdocs[a]);


                            }


                            homedata['B']={
                                bean:bartcdoc,
                                list:bchildren
                            };
                            rdata.layout=false;
                            rdata.homedata = homedata;
                            res.render('frontal/index',rdata);
                            db.close();

                            //----------------------------------------


                        });

                    });



                });








        });


    });


}


module.exports = function(app,i18n){
    routers.init(app,getRules(i18n));
    app.get('/child/:id',function(req,res){
        var arcId = req.params.id;
        req.body={"articlec.id":arcId};
        routers.proxyHttpWithDb(req, res, showChild);
    });
    app.get('/child/:id/:p',function(req,res){
        var arcId = req.params.id;
        var p  = req.params.p;
        res.redirect('/child/'+arcId+"?p="+p);
    });

    app.get('/detail/:id',function(req,res){
        routers.proxyHttpWithDb(req, res, showChildDetail);
    });
    app.get('/',function(req,res){
        routers.proxyHttpWithDb(req, res, homeData);
    });
}